#include <vector>
#include <fstream>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

#include "User.h"
#include "System.h"
#include "SystemPreferences.h"
#include "AppList.h"

System::System() :
  _connected(NULL)//,
{
  User* u1 = new User("Romain");
  User* u2 = new User("Aurelie");
  User* u3 = new User("Alban");

  _users.push_back(u1);
  _users.push_back(u2);
  _users.push_back(u3);
  _sysprefs = new SystemPreferences();
}

System::System(int argc, char** argv) {
}

System* System::SystemFactory(std::string file) {
  System* sp = new System();
  {
    std::ifstream ifs(file.c_str());
    boost::archive::text_iarchive ia(ifs);
    ia >> sp;
  }

 // _connected = _users.front();

  return sp;
}

System::~System() {
  if (_sysprefs) {
    delete _sysprefs;
  }

  for (unsigned int i = 0; i < _users.size(); i++) {
    removeUser(_users[i]);
  }
}

void System::setPreferences(SystemPreferences* prefs) {
  if (prefs) {
    _sysprefs = prefs;
  }
}

SystemPreferences& System::getPreferences() {
  return *_sysprefs;
}

void System::addUser(User* user) {
  if (user) {
    _users.push_back(user);
  }
}

void System::addUser(std::string file) {

}

void System::removeUser(User* user) {
  if (user) {
    delete user;
  }
}

void System::setConnectedUser(User& user) {
  *_connected = user;
}

User& System::getConnectedUser() {
  return *_connected;
}

AppList* System::getConnectedUserAppList() {
  return _connected->getAppList();
}

void System::saveConfiguration(std::string file) {
  std::ofstream outFile(file.c_str());
  {
    boost::archive::text_oarchive outArchive(outFile);
    outArchive << this;
  }
}

template<class Archive>
void System::serialize(Archive & ar, const unsigned int version) {
  ar & _sysprefs;
  ar & _users;
  // ar & _connected;
}
